import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 如果本地中有就取本地，否则为 undefined 或者 null
    username: localStorage.getItem('username'),
    userId: localStorage.getItem('userId'),
    token: localStorage.getItem('token'),
    routes: JSON.parse(localStorage.getItem('routes') || '[]'), // 后端返回的
    initRoutes: [] // 处理之后的路由
  },
  getters: {
  },
  mutations: {
    loginMutation(state, user) {
      state.username = user.username;
      state.userId = user.userId;
      state.token = user.token
    },
    setToken(state, token) {
      state.token = token
    },
    logoutMutation(state) {
      state.username = null;
      state.userId = null;
      state.token = null;
      state.routes = [];
      state.initRoutes = [];
    },
    setRoutes(state, routes) {
      state.routes = routes;
    },
    setInitRoutes(state, routes) {
      state.initRoutes = routes
    }
  },
  actions: {
    loginAction({ commit }, user) {
      return new Promise(resolve => {
        commit('loginMutation', {
          username: user.username,
          userId: user.userId,
          token: user.token
        });
        let routes = user.routes;
        routes.push({
          path: '*', redirect: '/404', title: '404', hidden: 0 // 404放最后
        })
        commit('setRoutes', routes);

        // 存入本地存储
        localStorage.setItem('username', user.username);
        localStorage.setItem('userId', user.userId);
        localStorage.setItem('token', user.token);
        localStorage.setItem('routes', JSON.stringify(routes));
        resolve();
      })
    },
    logoutAction({ commit }) {
      return new Promise((resolve) => {
        commit('logoutMutation');
        localStorage.clear();
        resolve();
      })
    },
    setRoutesActions({ commit }, routes) {
      commit('setRoutes', routes);
      localStorage.setItem('routes', JSON.stringify(routes));
    }
  }
})
